import React, { useState, useEffect } from 'react'
import { Table, Upload, Button, message } from 'antd'
import { RcFile } from 'antd/lib/upload/interface'
import { fetchFileList } from '../../servicer';
import axios from 'axios'
interface FileItemType {
	extname: string
	filename: string
	id: string
	size: number
	url: string
}

const Index: React.FC = () => {
	const [list, setList] = useState<FileItemType[]>([]);

	const fetchList = async () => {
		const resp = await fetchFileList()
		setList(resp.data.data)
	}
	const columns = [{
		title: 'ID',
		dataIndex: 'id',
		key: 'id',
	}, {
		title: '文件名称',
		dataIndex: 'filename',
		key: 'filename',
	}, {
		title: '文件类型',
		dataIndex: 'extname',
		key: 'extname',
	}, {
		title: '文件大小',
		dataIndex: 'size',
		key: 'size',
	}, {
		title: '文件路径',
		dataIndex: 'url',
		key: 'url',
	}, {
		title: '图片',
		dataIndex: 'url',
		key: 'url',
		render(_: string) {
			return <img width={50} height={50} src={_} alt="" />
		}
	}]

	const beforeUpload = (file: RcFile) => {
		if (!file.type.includes('image')) {
			message.error('上传的文件只可以是图片');
			return Upload.LIST_IGNORE
		}

		if (file.size >= 1 * 1024 * 1024) {
			message.error('上传的图片文件不可以超过1MB');
			return Upload.LIST_IGNORE
		}

		// 自己写上传逻辑
		const formData = new FormData();
		formData.append('file', file)

		axios.post('/api/upload', formData).then(resp => {
			fetchList()
		})

		return false
	}

	useEffect(() => {
		fetchList()
	}, [])

	return (
		<div>
			<div style={{
				height: 200,
				display: 'flex',
				justifyContent: 'center',
				alignItems: 'center'
			}}>
				<Upload action="/api/upload" beforeUpload={(file) => beforeUpload(file)}>
					<Button type="primary">上传文件</Button>
				</Upload>
			</div>
			<Table dataSource={list} columns={columns} rowKey={row => row.id}></Table>
		</div>
	)
}

export default Index;
